﻿using OF.DistributeService.Core.Common;
using OF.DistributeService.Core.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace OF.DistributeService.Core.Client.Entity
{

    public class AppGroupInstanceListHolder
    {
        private ClientConfig clientConfig = null;
        private ZooKeeperProxy zk;
        private string groupPath = null;
        private ClientToAppConfig clientToAppConfig = null;
        private List<InstanceServiceVersion> serviceVersionList = new List<InstanceServiceVersion>();

        public AppGroupInstanceListHolder(ClientConfig clientConfig, ZooKeeperProxy zk, ClientToAppConfig clientToAppConfig, string groupPath)
        {
            this.clientConfig = clientConfig;
            this.zk = zk;
            this.clientToAppConfig = clientToAppConfig;
            this.groupPath = groupPath;
        }

        public List<InstanceServiceVersion> GetCloneInstanceList()
        {
            return serviceVersionList.ToList();
        }

        public List<InstanceServiceVersion> GetInstanceList()
        {
            return serviceVersionList;
        }

        public void SetInstanceList(List<InstanceServiceVersion> serviceVersionList)
        {
            this.serviceVersionList = serviceVersionList;
        }

        public InstanceServiceVersion NewInstanceServiceVersion(string groupPath, string instance)
        {
            InstanceServiceVersion instanceVersion = new InstanceServiceVersion(this.clientConfig, instance, HttpUtility.UrlDecode(instance));
            byte[] data = zk.GetData(groupPath + "/" + instance, false, null);
            string[] serviceVersionArray = Util.GetMsgPackObject<string[]>(data);
            foreach (string serviceVersion in serviceVersionArray)
            {
                string[] arr = serviceVersion.Split(':');
                string serviceFullName = arr[0];
                var serviceConfig = clientToAppConfig.ServiceList.FirstOrDefault(service => service.ServiceName.Equals(serviceFullName));
                if (serviceConfig == null)
                {
                    continue;
                }
                string version = arr[1];
                ServiceVersionMethods serviceVersionMethods = new ServiceVersionMethods(serviceConfig.GetVirtualPath(), serviceConfig.GetMethodArray());
                instanceVersion.Add(ClientToAppManager.GetKey(new string[] { serviceFullName, version }), serviceVersionMethods);
            }
            return instanceVersion;
        }
    }

}
